package service.impl;

import bean.pojo.GdUser;
import com.alibaba.fastjson.JSON;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;
import service.TokenService;
import utils.MD5;
import utils.RedisAPI;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class TokenServiceImpl implements TokenService {
    @Resource
    RedisAPI redisAPI;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    /**
     * token:来源-id-时间-随机6位
     * @param userAgent
     * @param gdUser
     * @return
     */
    @Override
    public String generateToken(String userAgent,GdUser gdUser) throws Exception {

        StringBuilder sb = new StringBuilder();
        sb.append("token:");
        UserAgent agent = UserAgent.parseUserAgentString(userAgent);
        if (agent.getOperatingSystem().isMobileDevice())
            sb.append("MOBILE-");
        else sb.append("PC-");
        sb.append(MD5.getMD5(String.valueOf(gdUser.getId()),32)+"-");
        sb.append(sdf.format(new Date())+"-");
        sb.append(MD5.getMD5(userAgent,6));
        return sb.toString();
    }

    @Override
    public boolean saveToken(String token,GdUser gdUser) throws Exception {
        if (token.startsWith("token:PC-")){
            redisAPI.set(token,TokenService.SESSION_TIMEOUT,JSON.toJSONString(gdUser));
        }else {
            redisAPI.set(token,TokenService.SESSION_TIMEOUT,JSON.toJSONString(gdUser));
        }
        return false;
    }

    @Override
    public boolean validate(String userAgent,String token) throws Exception{
        if (!redisAPI.exists(token))
            return false;
        String tokenInfo[] = token.split("-");
        String genTime = tokenInfo[2];//生成时间
        if (redisAPI.ttl(token)<0&&redisAPI.ttl(token)!=-1)
            return false;
        if (!MD5.getMD5(userAgent,6).equals(tokenInfo[3])) {

            return false;
        }
        return true;
    }

    @Override
    public boolean delete(String token)  throws Exception{
        try{
            redisAPI.delete(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean replace(String token) throws Exception{
        if (redisAPI.ttl(token)<TokenService.REPLACEMENT_PROTECTION_TIMEOUT&&redisAPI.ttl(token)>0||redisAPI.ttl(token)==-1){
            String tokenInfo[] = token.split("-");
            GdUser user = getUser(token);
            redisAPI.set(token,TokenService.REPLACEMENT_DELAY,JSON.toJSONString(user));
            String newToken = generateToken(tokenInfo[0],user);
            saveToken(newToken,user);

            return true;
        }
        return false;
    }

    @Override
    public GdUser getUser(String token) throws Exception{
        if (!redisAPI.exists(token))
            return null;
        return JSON.parseObject(redisAPI.get(token),GdUser.class);
    }
}
